package com.lemon.smartsafety.ui.activity.safe.nfcandqrcode;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.view.SpacesItemDecoration;
import com.lemon.android.http.Field;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.CommonAssetsVo;
import com.lemon.smartsafety.entity.common.CommonVo;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.inspection.InspectionCheckItemStepTwoFinishEvent;
import com.lemon.smartsafety.entity.safe.company.FireCheckDetailVo;
import com.lemon.smartsafety.entity.safe.inspection.CompanyBuildingItemConclusionVo;
import com.lemon.smartsafety.entity.safe.inspection.CompanyBuildingItemFlowVo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.InspectionServices;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.result.safe.ResultCheckNfc;
import com.lemon.smartsafety.tag.BaseTAG;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.ui.adapter.safe.inspection.CheckItemFlowConclusionAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class CodeInspectionStepTwoActivity extends PhotoSelectBaseActivity implements RecyclerTClickListener<CompanyBuildingItemConclusionVo> {

    @Bind(R.id.tv_tip)
    TextView tvTip;
    @Bind(R.id.tv_check_flow_name)
    TextView         tvCheckFlowName;
    @Bind(R.id.ll_check_flow_name)
    LinearLayout llCheckFlowName;
    @Bind(R.id.tv_check_flow_remark)
    TextView         tvCheckFlowRemark;
    @Bind(R.id.ll_check_flow_remark)
    LinearLayout     llCheckFlowRemark;
    @Bind(R.id.tv_check_flow_last_check)
    TextView         tvCheckFlowLastCheck;
    @Bind(R.id.ll_check_flow_last_check)
    LinearLayout     llCheckFlowLastCheck;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.met_remark)
    MaterialEditText metRemark;
    @Bind(R.id.mSelectRecycleView)
    RecyclerView     mSelectRecycleView;//可以录音，可以拍照
    @Bind(R.id.btn_submit)
    Button btnSubmit;


    private LoggerHelper loggerHelper = new LoggerHelper(CodeInspectionStepTwoActivity.class);


    /**
     * bundle info
     */
    private ResultCheckNfc.FlowListEntity flowListEntity;
    private ResultCheckNfc resultCheckNfc;
    private CompanyBuildingItemFlowVo mCompanyBuildingItemFlowVo;


    private String                                sCheckId = "";
    private List<CompanyBuildingItemConclusionVo> mItems   = new ArrayList<>();

    private CheckItemFlowConclusionAdapter mAdapter;
    private CompanyBuildingItemConclusionVo selectedVo = null;
    private boolean                         isEdit     = false;
    private FireCheckDetailVo detailVo   = null;
    SpacesItemDecoration mItemDecoration;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            flowListEntity = (ResultCheckNfc.FlowListEntity) getIntent().getSerializableExtra(BaseTAG.ResultCheckNfc_CheckDATA);
            resultCheckNfc = (ResultCheckNfc) getIntent().getSerializableExtra(BaseTAG.ResultCheckNfc_ItemDATA);
            sCheckId = resultCheckNfc.getCheckId();
        }
    }

    @Override
    protected void initTitle() {
        setBarTitle(R.string.safe_title);
    }

    @Override
    protected void callFinish() {
        IApplication._tempTwoActivity = null;
        AppManager.getAppManager().finishActivity(CodeInspectionStepTwoActivity.this);
        System.gc();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_code_inspection_step_two;
    }


    @Override
    protected void initViews() {
        super.initViews();
        if(CommonUtil.objIsEmpty(flowListEntity)) {
            callFinish();
        }



        initViewValue();

        int spacingInPixels = recyclerView.getContext().getResources().getDimensionPixelSize(R.dimen.height_one_px);
        mItemDecoration = new SpacesItemDecoration(spacingInPixels);

        mAdapter = new CheckItemFlowConclusionAdapter(mItems, this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);
        recyclerView.addItemDecoration(mItemDecoration);


        getNetData();
        IApplication._tempTwoActivity = this;
    }


    private void initViewValue() {
        tvTip.setText(resultCheckNfc.getAddress());
        tvCheckFlowName.setText(StringUtils.nullValue(flowListEntity.getFlowName()).trim());
        tvCheckFlowRemark.setText(StringUtils.nullValue(flowListEntity.getCheckWay()).trim());
        //tvCheckFlowLastCheck.setText(StringUtils.nullValue(flowListEntity.getLastConClusionName().trim(), "无"));

    }


    @Override
    protected void initListener() {
        super.initListener();
    }


    private void getNetData() {
        sCheckId = StringUtils.nullValue(sCheckId);
        InspectionServices.init().getCheckItemFlowListDetail(flowListEntity.getFlowId(), sCheckId);
    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_INSPECTION_CHECK_ITEM_FLOW_CONCLUSION.equals(event.getTag())) {//获取检查流程数据
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.hidden();
                    setFlowList((CompanyBuildingItemFlowVo) event.getObj());
                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }
        } else if (EventTag.TAG_INSPECTION_CHECK_ITEM_FLOW_ACTION.equals(event.getTag())) {//保存
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    CommonVo vo          = (CommonVo) event.getObj();
                    final InspectionCheckItemStepTwoFinishEvent finishEvent = new InspectionCheckItemStepTwoFinishEvent();
                    finishEvent.setData(vo);
                    finishEvent.setTag(InspectionCheckItemStepTwoFinishEvent.class.getName());
                    mHUDUtil.showInfoTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            AppService.getBus().post(finishEvent);
                            callFinish();
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }
        }
    }


    private void setFlowList(CompanyBuildingItemFlowVo vo) {
        if (null != vo) {
            mCompanyBuildingItemFlowVo = vo;
        }
        initViewValue();

        String conclusionId = "";
        detailVo = mCompanyBuildingItemFlowVo.getFd();
        if (null != detailVo) {
            isEdit = true;
            metRemark.setText(StringUtils.nullValue(detailVo.getRemark()));//获取上一次的备注
            conclusionId = detailVo.getConclusionId();//获取上一次的结论ID
            if (detailVo.getAttestList() != null && detailVo.getAttestList().size() != 0) {
                handleAttest(detailVo.getAttestList());
            }
        }
        if (vo != null && vo.getList() != null && vo.getList().size() != 0) {
            mItems.clear();
            mItems.addAll(vo.getList());
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
        }

        if (isEdit && conclusionId.length() != 0) {
            setConclusionList(conclusionId);
        }
    }

    private void setConclusionList(String conclusionId) {
        for (int i = 0; i < mAdapter.getData().size(); i++) {
            CompanyBuildingItemConclusionVo vo = mAdapter.getData().get(i);
            if (vo != null && conclusionId.equals(vo.getConclusionId())) {
                vo.setChecked(true);
                selectedVo = vo;
            } else {
                vo.setChecked(false);
            }
        }

        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    //初始化上次的材料视图
    public void handleAttest(List<CommonAssetsVo> attestList) {
        addAllItems(attestList);
    }


    @Override
    public void onItemClick(CompanyBuildingItemConclusionVo data, int position) {
        selectedVo = data;
    }



    @Override
    public void evidencePlusEventHandler(String tag) {
        if (this.getClass().getName().equals(tag)) {
            showActionSheet(EvidenceActionSheetType.CAMERA_VOICE);
        }
    }

    @OnClick({R.id.btn_submit})
    public void submitClick(View view) {
        if (view.getId() == R.id.btn_submit) {
            if (!validateForm()) {
                return;
            }
            getConfirmDialog("是否提交？", new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        doSubmitAction();
                    }
                }
            }).show();

        }
    }

    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        if (null == selectedVo) {
            mHUDUtil.showErrorTip("请选择检查结论");
            return false;
        }
        return true;
    }

    private void doSubmitAction() {
        final LemonRequestParams params = new LemonRequestParams("fire_check_detail", "detail_id", "");
        params.put("user_id", mSharedPreferencesHelper.getUserId());
        params.put("item_id", mCompanyBuildingItemFlowVo.getItemId());
        params.put("txtCheckId", sCheckId, Field.TYPE_STRING);
        params.put("txtFlowId", mCompanyBuildingItemFlowVo.getFlowId(), Field.TYPE_INT);
        params.put("txtMarkCode", StringUtils.nullValue(selectedVo.getMarkCode()), Field.TYPE_STRING);
        params.put("txtConclusionId", StringUtils.nullValue(selectedVo.getConclusionId()), Field.TYPE_INT);
        params.put("txtRemark", metRemark.getText().toString().trim(), Field.TYPE_STRING);
        if (isEdit) {
            params.put("_txtIdValues", detailVo.getDetailId());
            params.put("detail_id", detailVo.getDetailId());
        } else {
            params.put("_txtIdValues", "");
            params.put("detail_id", "");
        }
        getUploadItems(new SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>>() {
            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mHUDUtil.showHUD();
                    }
                });
            }

            @Override
            public void onFinish(List<UploadFileItem> data) {
                if (data != null && data.size() != 0) {
                    params.put("files", mGson.toJson(data));
                }
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        InspectionServices.init().saveInspectionDetail(params, isEdit);
                    }
                });
            }
        });

    }


    /****************************************************************************************************************
     * 保护现场
     ****************************************************************************************************************/
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(BundleKey.SAFE_INSPECTION_FLOW, mCompanyBuildingItemFlowVo);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mCompanyBuildingItemFlowVo = (CompanyBuildingItemFlowVo) savedInstanceState.getSerializable(BundleKey.SAFE_INSPECTION_FLOW);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(EventTag.TAG_INSPECTION_CHECK_ITEM_FLOW_CONCLUSION);
        mCompanyBuildingItemFlowVo = null;
        IApplication._tempTwoActivity = null;
    }
}
